<template>
  <div class="pattern-container">
    <div class="header">
      <h2>排样方案可视化</h2>
      <div class="stats-header">
        <el-space :size="20">
          <el-tag type="info">当前方案数: {{ patternData.length }}个</el-tag>
          <el-tag type="success">总零件长度: {{ totalPartsLength }}mm</el-tag>
          <el-tag type="warning">总原料长度: {{ totalRawLength }}mm</el-tag>
          <el-tag type="danger">余料总长: {{ totalWaste }}mm</el-tag>
          <el-tag :type="totalUsage >= 85 ? 'success' : 'warning'">
            总利用率 {{ totalUsage }}%
          </el-tag>
        </el-space>
        <el-button type="primary" @click="generatePattern">生成新方案</el-button>
      </div>

      <div class="material-summary">
        <el-card shadow="never">
          <template #header>
            <span>原料使用汇总</span>
          </template>
          <el-table :data="materialList" size="small" border>
            <el-table-column prop="rawId" label="原料ID" width="120"/>
            <el-table-column prop="rawLength" label="长度(mm)" width="120"/>
            <el-table-column prop="totalUsage" label="使用次数" width="120"/>
            <el-table-column label="总消耗长度(mm)">
              <template #default="{row}">{{ row.rawLength * row.totalUsage }}</template>
            </el-table-column>
          </el-table>
        </el-card>
      </div>
    </div>

    <div class="schemes-container">
      <div 
        v-for="scheme in patternData" 
        :key="scheme.cuttingId" 
        class="scheme-item"
      >
        <div class="scheme-header">
          <div class="raw-info">
            <el-tag>原料ID: {{ scheme.rawId }}</el-tag>
            <el-tag type="warning">原料长度: {{ scheme.rawLength }}mm</el-tag>
            <el-tag type="success">使用次数: {{ scheme.castNum }}</el-tag>
          </div>
          <div class="usage-info">
            利用率 {{ calculateUsage(scheme) }}%
            ({{ totalUsedLength(scheme) }}/{{ scheme.rawLength }}mm)
          </div>
        </div>

        <div class="cutting-container" ref="container">
          <div 
            class="raw-bar" 
            :style="{
              width: `${scheme.rawLength * pixelRatio}px`,
              backgroundColor: '#f0f2f5'
            }"
          >
            <div
              v-for="(segment, index) in getSegments(scheme)"
              :key="index"
              class="cut-segment"
              :style="segmentStyle(segment)"
              :title="`零件ID: ${segment.partId}\n长度: ${segment.partLength}mm`"
            >
              <span class="segment-label">{{ segment.partLength }}mm</span>
            </div>
          </div>
        </div>

        <div class="parts-list">
          <div 
            v-for="(part, index) in scheme.cuttingList" 
            :key="index"
            class="part-item"
          >
            <div 
              class="color-marker" 
              :style="{backgroundColor: partColor(part.partId)}"
            ></div>
            <span class="part-id">#{{ part.partId }}</span>
            <span class="part-length">{{ part.partLength }}mm</span>
            <el-divider direction="vertical" />
            <span class="part-quantity">×{{ part.partNum }}</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'

const api = axios.create({
  baseURL: '/oneDimension',
  headers: { 'Content-Type': 'application/json' }
})

const patternData = ref([])
const container = ref(null)
const pixelRatio = ref(8)

// 原料使用汇总计算
const materialList = computed(() => {
  const map = new Map()
  patternData.value.forEach(scheme => {
    const existing = map.get(scheme.rawId)
    if (existing) {
      existing.totalUsage += scheme.castNum
    } else {
      map.set(scheme.rawId, {
        rawId: scheme.rawId,
        rawLength: scheme.rawLength,
        totalUsage: scheme.castNum
      })
    }
  })
  return Array.from(map.values())
})

// 新增余料计算属性
const totalWaste = computed(() => {
  return Math.max(totalRawLength.value - totalPartsLength.value, 0)
})

// 修正后的总零件长度计算
const totalPartsLength = computed(() => {
  return patternData.value.reduce((total, scheme) => {
    // 先计算单个方案的零件总长度
    const schemeTotal = scheme.cuttingList.reduce(
      (sum, part) => sum + part.partLength * part.partNum,
      0
    )
    // 乘以方案使用次数
    return total + schemeTotal * scheme.castNum
  }, 0)
})

// 修正后的总原料消耗计算
const totalRawLength = computed(() => {
  return patternData.value.reduce(
    (sum, scheme) => sum + scheme.rawLength * scheme.castNum,
    0
  )
})

// 利用率计算
const totalUsage = computed(() => {
  return totalRawLength.value > 0 
    ? ((totalPartsLength.value / totalRawLength.value) * 100).toFixed(2)
    : 0
})

// 单个方案的使用长度
const totalUsedLength = (scheme) => {
  return scheme.cuttingList.reduce(
    (sum, item) => sum + item.partLength * item.partNum,
    0
  )
}

// 单个方案利用率计算
const calculateUsage = (scheme) => {
  const used = totalUsedLength(scheme)
  return ((used / scheme.rawLength) * 100).toFixed(2)
}

// 颜色生成函数
const partColor = (partId) => {
  const hue = (partId * 137) % 360
  return `hsl(${hue}, 70%, 60%)`
}

// 生成切割段数据
const getSegments = (scheme) => {
  return scheme.cuttingList.flatMap(part => 
    Array(part.partNum).fill({
      partId: part.partId,
      partLength: part.partLength
    })
  )
}

// 切割段样式
const segmentStyle = (segment) => ({
  width: `${segment.partLength * pixelRatio.value}px`,
  backgroundColor: partColor(segment.partId),
  height: '40px'
})

// 生成排样方案
const generatePattern = async () => {
  try {
    const { data } = await api.get('/getPattern')
    if (data.code === 200) {
      patternData.value = data.data
      ElMessage.success(`生成${data.data.length}个排样方案`)
    }
  } catch (error) {
    ElMessage.error('方案生成失败')
    console.error('API错误:', error)
  }
}

// 自适应布局
onMounted(() => {
  const updateRatio = () => {
    const containerWidth = container.value?.offsetWidth || 800
    const maxRawLength = Math.max(...patternData.value.map(s => s.rawLength), 100)
    pixelRatio.value = Math.min(containerWidth / maxRawLength, 15)
  }
  
  window.addEventListener('resize', updateRatio)
  updateRatio()
})
</script>

<style scoped>
.pattern-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.header {
  margin-bottom: 24px;
}

.stats-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 16px 0;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 8px;
}

.material-summary {
  margin-top: 20px;
}

.scheme-item {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
  padding: 20px;
  margin-bottom: 24px;
}

.scheme-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 16px;
}

.raw-info {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.usage-info {
  color: #666;
  font-size: 14px;
  line-height: 32px;
}

.cutting-container {
  overflow-x: auto;
  padding: 12px 0;
}

.raw-bar {
  height: 40px;
  border-radius: 4px;
  position: relative;
  display: flex;
  gap: 2px;
}

.cut-segment {
  display: flex;
  align-items: center;
  justify-content: center;
  transition: transform 0.2s;
  position: relative;
  min-width: 40px;
}

.cut-segment:hover {
  transform: scaleY(1.1);
  z-index: 2;
}

.segment-label {
  color: white;
  font-size: 12px;
  padding: 2px 4px;
  background: rgba(0,0,0,0.5);
  border-radius: 3px;
}

.parts-list {
  margin-top: 16px;
  border-top: 1px solid #eee;
  padding-top: 12px;
}

.part-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px;
  margin: 4px 0;
}

.color-marker {
  width: 16px;
  height: 16px;
  border-radius: 3px;
}

.part-id {
  font-weight: 500;
  color: #333;
}

.part-length {
  color: #666;
}

.part-quantity {
  color: #409eff;
}

@media (max-width: 768px) {
  .stats-header {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }

  .scheme-header {
    flex-direction: column;
    gap: 8px;
  }
  
  .raw-bar {
    min-width: 100%;
  }
}
</style>